<template>
  <div class="p-2 mt20" >
    <!-- 添加或修改分销配置对话框 -->
    <el-form ref="brokerageConfigFormRef" :model="form" :rules="rules" label-width="120px">
      <el-tabs>
        <el-tab-pane label="分佣设置">
          <el-form-item label="分佣启用" prop="enableBrokerage">
            <el-switch
              v-model="form.enableBrokerage"
              size="large"
              active-value="1"
              active-text="启用"
              inactive-value="0"
              inactive-text="关闭"
            />
            <el-text size="small" type="info" style="width: 100%">是否开启分佣模式</el-text>
          </el-form-item>
          <el-form-item label="返佣比例" prop="firstPercent">
            <el-input-number v-model="form.firstPercent" :min="0" :max="100" step-strictly :step="1"
                             placeholder="请输入返佣比例"/>
            <el-text size="small" type="info" style="width: 100%">订单交易成功后给推广人返佣的百分比</el-text>
          </el-form-item>
          <el-form-item label="返佣上限金额" prop="maxAmountYuan">
            <el-input-number v-model="form.maxAmountYuan" :min="0" :precision="2" placeholder="请输入返佣上限金额"/>
            <el-text size="small" type="info" style="width: 100%">返佣金额上限，金额为零时表示不设置上限</el-text>
          </el-form-item>
          <el-form-item label="佣金冻结天数" prop="brokerageFrozenDay">
            <el-input-number v-model="form.brokerageFrozenDay" :min="0" step-strictly :step="1"
                             placeholder="请输入佣金冻结天数"/>
            <el-text size="small" type="info" style="width: 100%">
              防止用户退款，佣金被提现了，所以需要设置佣金冻结时间，单位：天
            </el-text>
          </el-form-item>
          <el-form-item label="提现最低金额" prop="withdrawMinPriceYuan">
            <el-input-number v-model="form.withdrawMinPriceYuan" :min="0" :precision="2"
                             placeholder="请输入提现最低金额"/>
            <el-text size="small" type="info" style="width: 100%">用户提现最低金额限制，单位：元</el-text>
          </el-form-item>
          <el-form-item label="提现手续费" prop="withdrawFeePercent">
            <el-input-number v-model="form.withdrawFeePercent" :min="0" :max="100" step-strictly :step="1"
                             placeholder="请输入提现手续费"/>
            <el-text size="small" type="info" style="width: 100%">提现手续费百分比，范围 0-100，0 为无提现手续费。例：设置
              10，即收取 10% 手续费，提现 10 元，到账 9 元，1 元手续费
            </el-text>
          </el-form-item>
          <el-form-item label="订单分成比例" prop="orderPercent">
            <el-input-number v-model="form.orderPercent" :min="0" :max="100" step-strictly :step="1"
                             placeholder="请输入订单分成比例"/>
            <el-text size="small" type="info" style="width: 100%">订单处理完成后给推广人订单分成的百分比</el-text>
          </el-form-item>
          <el-form-item label="分成上限金额" prop="orderProfitAmountYuan">
            <el-input-number v-model="form.orderProfitAmountYuan" :min="0" :precision="2" placeholder="请输入订单分成上限金额"/>
            <el-text size="small" type="info" style="width: 100%">订单分成金额上限，金额为零时表示不设置上限</el-text>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
      <el-form-item>
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup name="BrokerageConfig" lang="ts">
import {
  listBrokerageConfig,
  getBrokerageConfig,
  delBrokerageConfig,
  addBrokerageConfig,
  updateBrokerageConfig
} from '@/api/brokerage/config';
import { BrokerageConfigVo, BrokerageConfigQuery, BrokerageConfigForm} from '@/api/brokerage/config/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const brokerageConfigList = ref<BrokerageConfigVo[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const brokerageConfigFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: BrokerageConfigForm = {
  id: undefined,
  enableBrokerage: undefined,
  brokerageMode: undefined,
  bindMode: undefined,
  firstPercent: undefined,
  withdrawMinPrice: undefined,
  withdrawFeePercent: undefined,
  brokerageFrozenDay: undefined,
  withdrawType: undefined,
  enableMax: undefined,
  maxAmount: undefined,
  enableOrder: undefined,
  orderProfit: undefined,
  orderPercent: undefined
}
const data = reactive<PageData<BrokerageConfigForm, BrokerageConfigQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    enableBrokerage: undefined,
    brokerageMode: undefined,
    bindMode: undefined,
    firstPercent: undefined,
    withdrawMinPrice: undefined,
    withdrawFeePercent: undefined,
    brokerageFrozenDay: undefined,
    withdrawType: undefined,
    params: {}
  },
  rules: {
    firstPercent: [
      {required: true, message: "返佣比例不能为空", trigger: "blur"}
    ],
    withdrawMinPriceYuan: [
      {required: true, message: "提现最低金额不能为空", trigger: "blur"}
    ],
    brokerageFrozenDay: [
      {required: true, message: "佣金冻天数不能为空", trigger: "blur"}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询分销配置列表 */
const getList = async () => {
  loading.value = true;
  const res = await listBrokerageConfig(queryParams.value);
  brokerageConfigList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  brokerageConfigFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: BrokerageConfigVo[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加分销配置';
};

/** 修改按钮操作 */
const getBrokerageConfigInfo = async () => {
  reset();
  const res = await getBrokerageConfig();
  res.data.withdrawMinPriceYuan = res.data.withdrawMinPrice / 100;
  res.data.maxAmountYuan = res.data.maxAmount / 100;
  res.data.orderProfitAmountYuan = res.data.orderProfitAmount / 100;
  Object.assign(form.value, res.data);
};

/** 提交按钮 */
const submitForm = () => {
  brokerageConfigFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.withdrawMinPrice = form.value.withdrawMinPriceYuan * 100;
      form.value.maxAmount = form.value.maxAmountYuan * 100;
      form.value.orderProfitAmount = form.value.orderProfitAmountYuan * 100;
      if (form.value.id) {
        await updateBrokerageConfig(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addBrokerageConfig(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getBrokerageConfigInfo();
    }
  });
};

/** 删除按钮操作 */
// const handleDelete = async (row?: BrokerageConfigVo) => {
//   const _ids = row?.id || ids.value;
//   await proxy?.$modal.confirm('是否确认删除当前选中的数据项？').finally(() => loading.value = false);
//   await delBrokerageConfig(_ids);
//   proxy?.$modal.msgSuccess('删除成功');
//   await getList();
// }

onMounted(() => {
  getBrokerageConfigInfo();
});
</script>
